package com.meego.common.database.pool;

import java.util.HashMap;
import java.util.Map;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

public class BoneCPPool {
	private static final String driver = "com.mysql.jdbc.Driver";
	private Map<String, BoneCP> mPool;
	private static BoneCPPool sIntance;

	public static synchronized BoneCPPool getInstance() throws Exception{
		if (sIntance == null) {
			sIntance = new BoneCPPool();
		}
		return sIntance;
	}

	public BoneCPPool() throws Exception{
		mPool = new HashMap<String, BoneCP>();
		
		String url = "jdbc:mysql://192.168.11.222/nctid";
		String user = "root";
		String pass = "123456";
		
		// setup the connection pool
		BoneCPConfig config = new BoneCPConfig();
		config.setJdbcUrl(url);
		config.setUsername(user);
		config.setPassword(pass);
		config.setMinConnectionsPerPartition(2);
		config.setMaxConnectionsPerPartition(10);
		config.setPartitionCount(1);
		config.setTransactionRecoveryEnabled(true);
		config.setDefaultAutoCommit(true);
		config.setIdleMaxAgeInSeconds(30);
		config.setConnectionTimeoutInMs(40);
		config.setAcquireIncrement(5);
		config.setLazyInit(false);
		config.setReleaseHelperThreads(2);
		config.setIdleConnectionTestPeriodInMinutes(60);
		config.setAcquireRetryAttempts(3);
		config.setCloseConnectionWatchTimeoutInMs(30);
		config.setPoolName("default");
		
		initPool(config);
	}

	public BoneCP getBoneCP(String aPool) {
		return mPool.get(aPool);
	}

	public synchronized void initPool(BoneCPConfig config) throws Exception {
		Class.forName(driver);
		BoneCP pool = new BoneCP(config);
		this.mPool.put(config.getPoolName(), pool);
	}
}
